<?php

class Admin extends CActiveRecord
{
    public $admin_notpass;

    public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{admin}}';
	}

	public function rules()
	{
		return array(
			array('admin_name, admin_pass, admin_notpass', 'required', 'on'=>'create'),
			array('admin_name', 'unique', 'on'=>'create'),
			array('admin_name', 'hasUser', 'on'=>'update'),
			array('admin_name', 'required', 'on'=>'update'),
            array('admin_notpass', 'compare', 'compareAttribute'=>'admin_pass'),
			array('admin_name', 'length', 'max'=>10, 'min'=>3),
			array('admin_pass', 'length', 'max'=>40, 'min'=>6),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'admin_name' => '管理员名称',
			'admin_pass' => '管理员密码',
			'admin_last_ip' => '最后登录IP',
			'admin_last_time' => '最后登录时间',
			'admin_reg_time' => '注册时间',
            'admin_notpass' => '确认密码',
		);
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('admin_name',$this->admin_name,true);
		$criteria->compare('admin_pass',$this->admin_pass,true);
		$criteria->compare('admin_last_ip',$this->admin_last_ip,true);
		$criteria->compare('admin_last_time',$this->admin_last_time,true);
		$criteria->compare('admin_reg_time',$this->admin_reg_time,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

    // 在插入之前进行的操作
    public function beforeSave()
    {
        if(parent::beforeSave())
        {
            // 加密密码
            $this->admin_pass = sha1($this->admin_pass);
            return true;
        }
        else
            return false;
    }

    // 更新时检查user用户名是否存在
    public function hasUser()
    {
        // 获取原来的名字
        $oldAdmin = $this->findByPk((int)$_GET['id']);
        $oldAdminName = $oldAdmin->admin_name;

        $admin = $this->findByAttributes(array('admin_name'=>$this->admin_name));
        if($admin->admin_name && $oldAdminName != $admin->admin_name)
            $this->addError('admin_name', '管理员名称'.$this->admin_name.'被占用');
    }

	public function onChange()
	{
		$this->raiseEvent('onChange', new CEvent($this));
	}
}